package cn.gov.cbrc.east.task;

import java.io.File;

import org.apache.logging.log4j.Level;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.core.Appender;
import org.apache.logging.log4j.core.LoggerContext;
import org.apache.logging.log4j.core.appender.FileAppender;
import org.apache.logging.log4j.core.config.AppenderRef;
import org.apache.logging.log4j.core.config.Configuration;
import org.apache.logging.log4j.core.config.LoggerConfig;
import org.apache.logging.log4j.core.layout.PatternLayout;

import cn.gov.cbrc.east.util.FileUtil;

public class JobLogFactory {
	
	private static final LoggerContext ctx = (LoggerContext) LogManager.getContext(false);
	
	private static final Configuration config = ctx.getConfiguration();
	
	private static String logDir = System.getProperty("user.dir")+File.separator;
	
	private static String prefix = "job";
	
	private JobLogFactory(){}
	
	/**
	 * <p>方法描述:启用日志文件 </p>
	 * <p>方法备注: </p>
	 * @param jobId
	 * <p>创建人：王川</p>
	 * <p>创建时间：Jan 14, 2016 10:55:08 AM</p>
	 *
	 */
	public static void start(String jobId){
	    PatternLayout layout = PatternLayout.createLayout(PatternLayout.DEFAULT_CONVERSION_PATTERN, config, null, null, true, false, null, null);
	    Appender appender = FileAppender.createAppender(
	    		logDir+String.format("logs/"+prefix+"-%s.log", jobId), "true", "false", 
	        jobId, null, "true", "true", null, layout, null, null, null, config);
	    appender.start();
	    config.addAppender(appender);
	    AppenderRef ref = AppenderRef.createAppenderRef(jobId, null, null);
	    AppenderRef[] refs = new AppenderRef[]{ref};
	    LoggerConfig loggerConfig = LoggerConfig.createLogger("false", Level.ALL, jobId, "true", refs, null, config, null);
	    loggerConfig.addAppender(appender, null, null);
	    config.addLogger(jobId, loggerConfig);
	    ctx.updateLoggers();
	}
	
	 /**
	 * <p>方法描述:停止日志文件 </p>
	 * <p>方法备注: </p>
	 * @param jobId
	 * <p>创建人：王川</p>
	 * <p>创建时间：Jan 14, 2016 10:54:45 AM</p>
	 *
	 */
	public static void stop(String jobId) {
		config.getAppender(jobId).stop();
		config.getLoggerConfig(jobId).removeAppender(jobId);
		config.removeLogger(jobId);
		ctx.updateLoggers();
	}
	
	/**
	 * <p>方法描述:删除日志文件 </p>
	 * <p>方法备注: </p>
	 * @param jobId
	 * <p>创建人：王川</p>
	 * <p>创建时间：Jan 14, 2016 10:56:20 AM</p>
	 *
	 */
	public static void delete(String jobId){
		String filePath = logDir+String.format("logs/job-%s.log", jobId);
		FileUtil.deleteFile(filePath);
	}
	 
	  /**
	 * <p>方法描述:获取logger </p>
	 * <p>方法备注: </p>
	 * @param jobId
	 * @return
	 * <p>创建人：王川</p>
	 * <p>创建时间：Jan 14, 2016 10:54:36 AM</p>
	 *
	 */
	public static Logger createLogger(String jobId) {
		start(jobId);
		return LogManager.getLogger(jobId);
	}
}
